package com.calendar.api.service.impl;

import com.calendar.api.model.SubTask;
import com.calendar.api.model.Task;
import com.calendar.api.model.User;
import com.calendar.api.model.dto.SubTaskDTO;
import com.calendar.api.model.dto.TaskDTO;
import com.calendar.api.repository.TaskRepository;
import com.calendar.api.repository.UserRepository;
import com.calendar.api.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {

    private final TaskRepository taskRepository;
    private final UserRepository userRepository;

    @Autowired
    public TaskServiceImpl(TaskRepository taskRepository, UserRepository userRepository) {
        this.taskRepository = taskRepository;
        this.userRepository = userRepository;
    }

    @Override
    public List<Task> getTasks(String categoryId, Long userId) {
        User user = getUserById(userId);
        if (categoryId != null && !categoryId.isEmpty() && !categoryId.equals("all")) {
            return taskRepository.findByCategoryIdAndUser(categoryId, user);
        }
        return taskRepository.findByUser(user);
    }

    @Override
    public Task getTask(Long id, Long userId) {
        Task task = taskRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("任务不存在: " + id));
        
        // 验证任务所属用户
        if (!task.getUser().getId().equals(userId)) {
            throw new EntityNotFoundException("任务不存在: " + id);
        }
        
        return task;
    }

    @Override
    public Task createTask(TaskDTO taskDTO, Long userId) {
        User user = getUserById(userId);
        Task task = convertToEntity(taskDTO);
        task.setUser(user);
        return taskRepository.save(task);
    }

    @Override
    public Task updateTask(Long id, TaskDTO taskDTO, Long userId) {
        Task existingTask = getTask(id, userId);
        
        existingTask.setTitle(taskDTO.getTitle());
        existingTask.setDescription(taskDTO.getDescription());
        existingTask.setDueDate(LocalDate.parse(taskDTO.getDueDate()));
        existingTask.setDueTime(taskDTO.getDueTime());
        existingTask.setPriority(taskDTO.getPriority());
        existingTask.setCategoryId(taskDTO.getCategoryId());
        existingTask.setCompleted(taskDTO.isCompleted());
        
        // 更新子任务
        existingTask.getSubtasks().clear();
        if (taskDTO.getSubtasks() != null) {
            for (SubTaskDTO subTaskDTO : taskDTO.getSubtasks()) {
                SubTask subTask = new SubTask();
                subTask.setTitle(subTaskDTO.getTitle());
                subTask.setCompleted(subTaskDTO.isCompleted());
                existingTask.getSubtasks().add(subTask);
            }
        }
        
        return taskRepository.save(existingTask);
    }

    @Override
    public void deleteTask(Long id, Long userId) {
        Task task = getTask(id, userId);
        taskRepository.delete(task);
    }

    @Override
    public Task toggleTaskStatus(Long id, Long userId) {
        Task task = getTask(id, userId);
        task.setCompleted(!task.isCompleted());
        return taskRepository.save(task);
    }

    @Override
    public List<Task> getTasksByDueDate(LocalDate dueDate, Long userId) {
        User user = getUserById(userId);
        return taskRepository.findByDueDateAndUser(dueDate, user);
    }
    
    private Task convertToEntity(TaskDTO taskDTO) {
        Task task = new Task();
        task.setTitle(taskDTO.getTitle());
        task.setDescription(taskDTO.getDescription());
        task.setDueDate(LocalDate.parse(taskDTO.getDueDate()));
        task.setDueTime(taskDTO.getDueTime() != null ? taskDTO.getDueTime() : "23:59");
        task.setPriority(taskDTO.getPriority());
        task.setCategoryId(taskDTO.getCategoryId());
        task.setCompleted(taskDTO.isCompleted());
        
        List<SubTask> subtasks = new ArrayList<>();
        if (taskDTO.getSubtasks() != null) {
            for (SubTaskDTO subTaskDTO : taskDTO.getSubtasks()) {
                SubTask subTask = new SubTask();
                subTask.setTitle(subTaskDTO.getTitle());
                subTask.setCompleted(subTaskDTO.isCompleted());
                subtasks.add(subTask);
            }
        }
        task.setSubtasks(subtasks);
        
        return task;
    }
    
    private User getUserById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在: " + userId));
    }
} 